package project.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import project.server.handlers.Client;
import project.server.handlers.Messenger;
import project.server.handlers.OutboundMessages;
import project.server.handlers.Sessions;
import project.server.util.Logger;
import project.shared.util.Config;

public class ServerMain {
	private static int PORT;
	
	public static void main(String[] args) throws IOException{
		Logger logger = new Logger();
		Config cfg = new Config("config.cfg");
		PORT = cfg.getPort();
		
		Sessions activeSessions = new Sessions(logger);
		OutboundMessages outQueue = new OutboundMessages(logger);
		
		ServerSocket serv = new ServerSocket(PORT);
		System.out.println("Server startis...");
		
		new Messenger(activeSessions, outQueue);
		
		try{
			while(true){
				Socket sock = serv.accept();
				try{
					new Client(sock, activeSessions, outQueue, logger);
				}catch(IOException e){
					System.out.println("Socketi loomine ebaõnnestus");
					sock.close();
				}
			}
		}
		finally{
			logger.log("Server sulgus.");
			serv.close();
			logger.close();
		}
		
	}

}
